﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace FilterTest1
{
    public class MyExceptionFilter : IAsyncExceptionFilter
    {
        private readonly IWebHostEnvironment hostEnv;

        public MyExceptionFilter(IWebHostEnvironment hostEnv)
        {
            this.hostEnv = hostEnv;
        }

        public Task OnExceptionAsync(ExceptionContext context)
        {
            //context.ActionDescriptor:ActionDescriptor:action的描述信息:
            //context.ActionDescriptor.DisplayName:action名字
            //context.ActionDescriptor.Parameters:action的参数等

            //发生异常的异常对象
            //context.Exception;
            //该异常是否被处理,如果设置为true,其他的ExceptionFilter就不会执行了
            //如果没有设置,当该ExceptionFilter,执行完成后会执行其他的ExceptionFilter
            //context.ExceptionHandled
            //给到浏览器响应的内容,它是一个IActionResult类型
            //context.Result
            
            string msg;

            if (hostEnv.IsDevelopment())
            {
                msg = context.Exception.Message;
            }
            else
            {
                msg = "服务器端发生未处理异常";
            }

            ObjectResult objectResult = new ObjectResult(new { code=500,message=msg });
            context.Result = objectResult;
            context.ExceptionHandled = true;

            return Task.CompletedTask;

        }
    }
}
